package com.dameng.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dameng.system.entity.SystemDept;
import com.dameng.system.entity.SystemRole;
import com.dameng.system.entity.SystemUser;
import com.dameng.system.entity.SystemUserRole;
import com.dameng.system.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/systemUser")
public class SystemUserController {

    @Resource
    SystemUserService systemUserService;

    @Resource
    SystemDeptService systemDeptService;

    @Resource
    SystemRoleService systemRoleService;

    @Resource
    SystemUserRoleService systemUserRoleService;

    @GetMapping("/manager")
    public String manager() {
        return "/system/User/manager";
    }

    @PostMapping("/deptList")
    @ResponseBody
    public List<SystemDept> deptList() {
        return systemDeptService.list();
    }

    @PostMapping("/list")
    @ResponseBody
    public Page<SystemUser> list(int page, int limit, SystemUser systemUser) {
        Page<SystemUser> page1 = new Page<>(page, limit);
        return systemUserService.getUserList(page1, systemUser);
    }

    @PostMapping("/checkExist")
    @ResponseBody
    public boolean checkExist(String username) {
        int count = systemUserService.count(
                new QueryWrapper<SystemUser>().lambda().eq(SystemUser::getUsername, username)
        );
        if (count > 0) {
            return true;
        }
        return false;
    }

    @GetMapping("/add")
    public String add(ModelMap model, SystemUser systemUser) {
        model.addAttribute("systemUser", systemUser);
        model.addAttribute("type", "save");
        return "/system/User/edit";
    }

    @PostMapping("/save")
    @ResponseBody
    @Transactional
    public boolean save(SystemUser systemUser) {
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodedPassword = passwordEncoder.encode(systemUser.getPassword());
        systemUser.setPassword(encodedPassword);
        if (null == systemUser.getStatus()) {
            systemUser.setStatus(false);
        }
        return systemUserService.save(systemUser);
    }

    @GetMapping("/edit")
    public String edit(ModelMap model, String userId) {
        QueryWrapper<SystemUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(SystemUser::getUserId, userId);
        SystemUser systemUser = systemUserService.getUserAndDept(wrapper);
        systemUser.setPassword("");
        model.addAttribute("systemUser", systemUser);
        model.addAttribute("type", "update");
        return "/system/User/edit";
    }

    @PostMapping("/update")
    @ResponseBody
    @Transactional
    public boolean update(SystemUser systemUser) {
        if (StringUtils.isNotEmpty(systemUser.getPassword())) {
            PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            String encodedPassword = passwordEncoder.encode(systemUser.getPassword());
            systemUser.setPassword(encodedPassword);
        } else {
            systemUser.setPassword(null); //设为null不更新该字段
        }
        if (null == systemUser.getStatus()) {
            systemUser.setStatus(false);
        }
        systemUser.setPwdModifyTime(new Date());
        return systemUserService.updateById(systemUser);
    }

    @GetMapping("/userRole")
    public String userRole(ModelMap model, SystemUser systemUser) {
        systemUser = systemUserService.getById(systemUser.getUserId());
        model.addAttribute("systemUser", systemUser);
        return "/system/User/userRole";
    }

    @PostMapping("/roleList")
    @ResponseBody
    public Page<SystemRole> roleList(String userId) {
        Page<SystemRole> page1 = new Page<>(0, 100);
        return systemRoleService.getRolesByUserId(page1, userId);
    }

    @PostMapping("/updateRole")
    @ResponseBody
    @Transactional
    public boolean updateRole(String userId, String... roleIds) {
        QueryWrapper<SystemUserRole> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(SystemUserRole::getUserId, userId);
        systemUserRoleService.remove(wrapper);

        List<SystemUserRole> userRoles = new ArrayList<>();
        List<String> ids = Arrays.asList(roleIds);
        for (String roleId : ids) {
            SystemUserRole userRole = new SystemUserRole().setUserId(userId).setRoleId(roleId);
            userRoles.add(userRole);
        }
        return systemUserRoleService.saveBatch(userRoles);
    }

    @PostMapping("/delete")
    @ResponseBody
    @Transactional
    public boolean delete(String... userIds) {
        List<String> ids = Arrays.asList(userIds);
        systemUserRoleService.removeByIds(ids);
        return systemUserService.removeByIds(ids);
    }

    @PostMapping("/enabled")
    @ResponseBody
    @Transactional
    public boolean enabled(boolean enabled, String... userIds) {
        SystemUser systemUser = new SystemUser();
        systemUser.setStatus(enabled);

        List<String> ids = Arrays.asList(userIds);
        UpdateWrapper<SystemUser> wrapper = new UpdateWrapper<>();
        wrapper.lambda().in(SystemUser::getUserId, ids);
        return systemUserService.update(systemUser, wrapper);
    }
}
